//
//  PackageViewController.m
//  UI_HLJ_Frame
//
//  Created by dllo on 15/6/30.
//  Copyright (c) 2015年 毕宏伟. All rights reserved.
//

#import "PackageViewController.h"

#import "PackageModel.h"
#import "CaseModel.h"
#import "NewMerchantModel.h"

#import "AFNetworking.h"


#import "UIImageView+WebCache.h"

#import "PackageCell.h"
#import "CaseCell.h"
#import "MerchantCell.h"

#import "PackageDetailsViewController.h"
#import "CaseDetailsViewController.h"
#import "MerchantDetailsViewController.h"

#import "PackageCollectionViewCell.h"
// 拼接id
#import "PackageDetailsViewController.h"
#import "CaseDetailsViewController.h"
#import "MerchantDetailsViewController.h"
#import "MBProgressHUD.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface PackageViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDelegate>
@property(nonatomic, retain)UITableView *packageTableView;


@property(nonatomic, retain)NSMutableArray *packageArr;
@property(nonatomic, retain)NSMutableArray *packageMerchantArr;
@property(nonatomic, retain)NSMutableArray *caseArr;
@property(nonatomic, retain)NSMutableArray *merchantArr;
@property(nonatomic, retain) NSIndexPath *indexPath;

@property(nonatomic,retain)UISegmentedControl *segmentedControl;
@property(nonatomic,retain)MBProgressHUD *hud;


@end

@implementation PackageViewController

- (void)dealloc
{
    [_collectionView release];
    [_packageStr release];
    [_caseStr release];
    [_merchantStr release];
    [_packageTableView release];
    [_packageArr release];
    [_packageMerchantArr release];
    [_caseArr release];
    [_merchantArr release];
    [_indexPath release];
    [_segmentedControl release];
    [_hud release];
    [_packageDic release];
    [_caseDic release];
    [_merchantDic release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    
    self.packageArr = [NSMutableArray array];
    self.packageMerchantArr = [NSMutableArray array];
    self.caseArr = [NSMutableArray array];
    self.merchantArr = [NSMutableArray array];
    
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"套餐",@"案例",@"商家",nil];
    
    self.segmentedControl= [[UISegmentedControl alloc]initWithItems:segmentedArray];
    
    
    self.segmentedControl.frame=CGRectMake(0, 0, WIDTH/2, 30);
    [self.segmentedControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];
    self.segmentedControl.tintColor=[UIColor colorWithRed:1.000 green:0.404 blue:0.651 alpha:1.000];
//    self.segmentedControl.enabled = NO;
        self.segmentedControl.layer.masksToBounds=NO;
    [self.view addSubview:self.segmentedControl];
    self.navigationItem.titleView = self.segmentedControl;
    [_segmentedControl release];

    self.hud = [[MBProgressHUD alloc] init];
    [self.view addSubview:self.hud];
    [self.hud show:YES];
    self.hud.labelText = @"loading...";
    
    
    // 数据解析
    [self creatData];

}
- (void)creatCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 横向滑动
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;//最小行距
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flowLayout];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    
    // 注册
    [self.collectionView registerClass:[PackageCollectionViewCell class] forCellWithReuseIdentifier:@"packageReuse"];
    [self.view addSubview:self.collectionView];
    
    
    
}

#pragma mark UICollectionViewCell
// 定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
    
}


// 每个UICollectionView展示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    PackageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"packageReuse" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor colorWithRed:0.438 green:1.000 blue:0.460 alpha:1.000];
    
    self.indexPath = indexPath;
    if (indexPath.row == 0) {
        if (self.packageArr) {
            
            cell.packageArr = self.packageArr;
            cell.flag = indexPath.row;

            cell.packageTableView.delegate = self;
            [cell.packageTableView setRowHeight:HEIGHT / 2];
            
            self.segmentedControl.selectedSegmentIndex = indexPath.row;

        }
    }else if (indexPath.row == 1){
        if (self.caseArr) {
            
            cell.caseArr = self.caseArr;
            cell.flag = indexPath.row;
            cell.packageTableView.delegate = self;
            [cell.packageTableView setRowHeight:HEIGHT / 2];
            
            self.segmentedControl.selectedSegmentIndex = indexPath.row;
        }
    }else{
        if (self.merchantArr) {
            cell.merchantArr = self.merchantArr;
            cell.flag = indexPath.row;
            cell.packageTableView.delegate = self;
            [cell.packageTableView setRowHeight:HEIGHT / 6];
            
            self.segmentedControl.selectedSegmentIndex = indexPath.row;
        }
    }
    return cell;
}


- (void)creatData
{
    
    
    

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[NSString stringWithFormat:self.packageStr, nil] parameters:self.packageDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *packageDic = responseObject;
        NSMutableArray *packageArr = packageDic[@"works"];
        
         //进行forin遍历,根据字典对modle进行赋值
        for (NSDictionary *tempDic in packageArr) {
            PackageModel *packageModel = [[PackageModel alloc] initWithDic:tempDic];
            [self.packageArr addObject:packageModel];
            [packageModel release];
        }
        
        
        AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
        [manager1 GET:[NSString stringWithFormat:self.caseStr, nil] parameters:self.caseDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *caseDic = responseObject;
            NSMutableArray *caseArr = caseDic[@"works"];
            
            // 进行forin遍历,根据字典对modle进行赋值
            for (NSDictionary *tempDic in caseArr) {
                CaseModel *caseModel = [[CaseModel alloc] initWithDic:tempDic];
                [self.caseArr addObject:caseModel];
                [caseModel release];
            }
            
            AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
            [manager2 GET:[NSString stringWithFormat:self.merchantStr, nil] parameters:self.merchantDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *merchantDic = responseObject;
                NSMutableArray *merchantArr = merchantDic[@"merchants"];
                
                // 进行forin遍历,根据字典对modle进行赋值
                for (NSDictionary *tempDic in merchantArr) {
                    NewMerchantModel *merchantModel = [[NewMerchantModel alloc] initWithDic:tempDic];
                    [self.merchantArr addObject:merchantModel];
                    [merchantModel release];
                }
                
                [self.collectionView reloadData];
                
                [self.hud hide:YES];
                // 创建一个collectionView
                [self creatCollectionView];
                
                
//                [self.collectionView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
            
            
//            [self.collectionView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
        
//        [self.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
//    NSURL *url = [NSURL URLWithString:self.packageStr];
//
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        // 在block中处理数据
//        NSMutableDictionary *packageDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//        NSMutableArray *packageArr = packageDic[@"works"];
//       
//        // 进行forin遍历,根据字典对modle进行赋值
//        for (NSDictionary *tempDic in packageArr) {
//            PackageModel *packageModel = [[PackageModel alloc] initWithDic:tempDic];
//            [self.packageArr addObject:packageModel];
//            [packageModel release];
//            
//            
//        }
//        
////        NSLog(@"%@", self.packageArr);
////        [self.collectionView reloadData];
//        
//        //------------
//        NSURL *caseUrl = [NSURL URLWithString:self.caseStr];
//        NSMutableURLRequest *caseRequest = [NSMutableURLRequest requestWithURL:caseUrl];
//        [NSURLConnection sendAsynchronousRequest:caseRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//            // 在block中处理数据
//            NSMutableDictionary *caseDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//            NSMutableArray *caseArr = caseDic[@"works"];
//            // 进行forin遍历,根据字典对modle进行赋值
//            for (NSDictionary *tempDic in caseArr) {
//                CaseModel *caseModel = [[CaseModel alloc] initWithDic:tempDic];
////                NSLog(@"%@",caseModel.coverpath);
//                [self.caseArr addObject:caseModel];
//                [caseModel release];
//            }
//            //        NSLog(@"%@", self.caseArr);
////            [self.collectionView reloadData];
//            
//            NSURL *merchantUrl = [NSURL URLWithString:self.merchantStr];
//            NSMutableURLRequest *merchantRequest = [NSMutableURLRequest requestWithURL:merchantUrl];
//            [NSURLConnection sendAsynchronousRequest:merchantRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//                // 在block中处理数据
//                NSMutableDictionary *merchantDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                NSMutableArray *merchantArr = merchantDic[@"merchants"];
//                // 进行forin遍历,根据字典对modle进行赋值
//                for (NSDictionary *tempDic in merchantArr) {
//                    NewMerchantModel *merchantModel = [[NewMerchantModel alloc] initWithDic:tempDic];
//                    [self.merchantArr addObject:merchantModel];
//                    [merchantModel release];
//                }
//                //        NSLog(@"%@", self.merchantArr);
//                [self.collectionView reloadData];
////
//                self.segmentedControl.selected = YES;
//                
//                
//                [self.hud hide:YES];
//
//                // 创建一个collectionView
//                [self creatCollectionView];
//
//                
//                
//            }];
//            
//        }];
//        
//
//    }];
    
    
    


    

    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.indexPath.row == 0) {
        
        PackageDetailsViewController *packageDetailsViewController = [[PackageDetailsViewController alloc] init];
        PackageModel *packageModel = self.packageArr[indexPath.row];
        packageDetailsViewController.idStr = packageModel.id;
//        PackageCell *cell = (PackageCell *)[self.packageTableView cellForRowAtIndexPath:indexPath];
//        
//        NSLog(@"%g,%g", cell.packageImageView.image.size.width, cell.packageImageView.image.size.height);
//        
        [self.navigationController pushViewController:packageDetailsViewController animated:YES];
    }else if (self.indexPath.row == 1){
        CaseDetailsViewController *caseDetailsViewController = [[CaseDetailsViewController alloc] init];
        CaseModel *caseModel = self.caseArr[indexPath.row];
        caseDetailsViewController.caseIdStr = caseModel.id;
        
        
//        [self.navigationController pushViewController:caseDetailsViewController animated:YES];

    }else{
        MerchantDetailsViewController *merchantDetailsViewController = [[MerchantDetailsViewController alloc] init];
        NewMerchantModel *newMerchantModel = self.merchantArr[indexPath.row];
        merchantDetailsViewController.merchantIdStr = newMerchantModel.id;
       
        merchantDetailsViewController.mer = newMerchantModel;
        
        merchantDetailsViewController.nameStr=newMerchantModel.name;
        merchantDetailsViewController.addressStr=newMerchantModel.address;
        merchantDetailsViewController.coverStr=newMerchantModel.cover_path;
        merchantDetailsViewController.logoStr=newMerchantModel.logopath;
        [self.navigationController pushViewController:merchantDetailsViewController animated:YES];
    }
    
}

- (void)segmentAction:(UISegmentedControl *)seg{
    if (seg.selectedSegmentIndex == 0) {
        self.collectionView.contentOffset = CGPointMake(WIDTH * seg.selectedSegmentIndex, 0);
//        [self.collectionView reloadData];
    }else if (seg.selectedSegmentIndex == 1){
        self.collectionView.contentOffset = CGPointMake(WIDTH * seg.selectedSegmentIndex, 0);
//        [self.collectionView reloadData];
    }else if (seg.selectedSegmentIndex == 2){
        self.collectionView.contentOffset = CGPointMake(WIDTH * seg.selectedSegmentIndex, 0);
//        [self.collectionView reloadData];
    }
}
//走完viewDidload走这个方法
//-(void)viewWillAppear:(BOOL)animated{
    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    [[SDImageCache sharedImageCache] clearMemory];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
